const morgan = require("morgan");
const rfs = require("rotating-file-stream");
const { mkdir } = require("./index");
const path = require("path");
const fileUrl = require("./fileUrl");

let logPath = `${fileUrl.logPath}`; //日志路径
mkdir(logPath);

// create a rotating write stream
var accessLogStream = rfs.createStream("access.log", {
  interval: "1d", // rotate daily
  path: path.join(logPath, "log"),
});
morgan.token("requestParameters", function (req, res) {
  return JSON.stringify(req.query) || "-";
});
morgan.token("requestBody", function (req, res) {
  return JSON.stringify(req.body) || "-";
});
morgan.token("localDate", function (req, res) {
  return new Date().toLocaleString();
});

// create custom format，includes the custom token
morgan.format(
  "live-api",
  ":remote-addr :method :url :status :requestParameters :requestBody - :response-time ms [:localDate]"
);
// 导出一个中间件函数，用于记录请求日志到文件
module.exports = function () {
  return morgan("live-api", { stream: accessLogStream });
};
